import { _decorator, Component, Node, Prefab, NodePool, instantiate, Vec3, find } from 'cc'
const { ccclass, property } = _decorator;
import { GameManager } from './GameManager';
import { MagicBall } from './MagicBall';

@ccclass('Wand')
export class Wand extends Component {
    @property({type: Prefab})
    magicBall: Prefab = null!
    gameManager: GameManager = new GameManager()
    canvas: Node = null!
    player: Node = null!

    start() {
        this.canvas = find('Canvas')
        this.player = find('Canvas/Player')
        this.gameManager = this.canvas.getComponent(GameManager)
    }

    /** 
     * @zh
     * 发射魔法球。
    */
    shoot() {
        let count = 0
        for (let i=0; i<this.canvas.children.length; i++) {
            // 最多同时发射3个魔法球
            if (count>=3){
                return
            }

            let target = this.canvas.children[i]
            if (target.name == 'monster' || target.name == 'Boss' && target.active) {
                count += 1
                let ball = this.spawnBall()
                ball.getComponent(MagicBall).setTarget(target)
            }
        }
    }

    /** 
     * @zh
     * 生成魔法球节点。
    */
    spawnBall() {
        let ball = instantiate(this.magicBall)
        this.canvas.addChild(ball)
        ball.setSiblingIndex(5000)
        ball.setPosition(new Vec3(this.player.position))
        return ball
    }
}

